package com.atgugu.flink.chapter08;

import com.atgugu.flink.bean.LoginEvent;
import com.atgugu.flink.util.AtguiguUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

import java.util.List;

/**
 * @Author lzc
 * @Date 2022/4/8 9:00
    private Long userId;
    private String ip;
    private String eventType;
    private Long eventTime;
 */
public class Flink05_Project_High_Login {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        env
            .readTextFile("input/LoginLog.csv")
            .map(log -> {
                String[] data = log.split(",");
                return new LoginEvent(
                    Long.valueOf(data[0]),
                    data[1],
                    data[2],
                    Long.valueOf(data[3])
                );
            })
            .keyBy(LoginEvent::getUserId)
            .countWindow(2, 1)
            .process(new ProcessWindowFunction<LoginEvent, String, Long, GlobalWindow>() {
                @Override
                public void process(Long key,
                                    Context ctx,
                                    Iterable<LoginEvent> elements, // elements 是不是一定有2个元素? 不是
                                    Collector<String> out) throws Exception {
                    List<LoginEvent> list = AtguiguUtil.toList(elements);
                    if (list.size() == 2) {
                        LoginEvent event1 = list.get(0);
                        LoginEvent event2 = list.get(1);
    
    
                        String eventType1 = event1.getEventType();
                        String eventType2 = event2.getEventType();
    
    
                        Long time1 = event1.getEventTime();
                        Long time2 = event2.getEventTime();
    
                        // 都是失败, 并且时间差小于等于2 表示恶意登录
                        if ("fail".equals(eventType1) && "fail".equals(eventType2) && Math.abs(time1 - time2) <= 2) {
                            out.collect(key + " 在恶意登录");
                        }
                        
    
                    }
                }
            })
            .print();
            
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
